package com.ihelp.proxy;

import com.ihelp.annotation.UserCheckLogin;
import com.ihelp.annotation.UserCheckOperate;
import com.ihelp.entities.CommonResult;
import com.ihelp.pojo.*;
import com.ihelp.service.OrderService;
import com.ihelp.service.RequestService;
import com.ihelp.service.UserService;
import com.ihelp.util.AnnotationResolver;
import com.ihelp.util.CookieUtil;
import com.ihelp.util.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Map;
import java.util.Objects;

@Component
@Aspect
public class UserCheckProxy {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private RequestService requestService;
    @Autowired
    private OrderService orderService;

    @Pointcut("@annotation(com.ihelp.annotation.UserCheckLogin)")
    public void userCheckLoginPointCut() {
    }
    @Around("userCheckLoginPointCut() && @annotation(userCheckLogin)")
    @Order(value = 2)
    public Object userCheckLogin(ProceedingJoinPoint proceedingJoinPoint, UserCheckLogin userCheckLogin) {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest servletRequest = attributes.getRequest();
            String userJWT = CookieUtil.getCookies(servletRequest, "userJWT");
            //用户信息不存在抛异常
            Claims claims = jwtUtil.parseJWT(userJWT);
            Integer JWTUserId = claims.get("id", Integer.class);
            return proceedingJoinPoint.proceed();
        } catch (Throwable e) {
            return new CommonResult(401, "用户验证信息错误");
        }
    }


    @Pointcut("@annotation(com.ihelp.annotation.UserCheckOperate)")
    public void userCheckOperatePointCut() {
    }

    @Around("userCheckOperatePointCut() && @annotation(userCheckOperate)")
    @Order(value = 2)
    public Object userCheckOperate(ProceedingJoinPoint proceedingJoinPoint, UserCheckOperate userCheckOperate) {
        try {
            Object[] args = proceedingJoinPoint.getArgs();

            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest servletRequest = attributes.getRequest();
            String userJWT = CookieUtil.getCookies(servletRequest, "userJWT");

            Integer operateObjectId = (Integer) args[0];
            //用户信息不存在抛异常
            Claims claims = jwtUtil.parseJWT(userJWT);
            Integer JWTUserId = claims.get("id", Integer.class);
            //获取注解内指定的值
            String operateObjectType = userCheckOperate.operateObject();

            Object operateObject = null;

            Integer userId = null;
            Integer requestVisitorId = null;
            Integer orderVisitorId = null;
            Integer orderAccompanyerId = null;

            if (operateObjectType.equals("user")) {
                operateObject = userService.getUserById(operateObjectId);
                if (operateObject == null) {
                    return new CommonResult(204, "不存在id：" + operateObjectId + "的用户");
                } else {
                    //根据request对象获取其陪诊人id
                    User request = (User) operateObject;
                    userId = request.getId();
                }

            } else if (operateObjectType.equals("request")) {
                operateObject = requestService.getRequestById(operateObjectId);
                if (operateObject == null) {
                    return new CommonResult(204, "不存在id：" + operateObjectId + "的请求");
                } else {
                    //根据request对象获取其陪诊人id
                    RequestDTO request = (RequestDTO) operateObject;
                    requestVisitorId = request.getVisitorId();
                }

            } else if (operateObjectType.equals("order")) {
                operateObject = orderService.getOrderById(operateObjectId);
//                System.out.println("aaaaaa"+operateObject.toString());
                if (operateObject == null) {
                    return new CommonResult(204, "不存在id：" + operateObjectId + "的订单");
                } else {
                    //根据order对象获取其陪诊人id
                    OrderDTO order = (OrderDTO) operateObject;
//                    System.out.println(order.toString());
                    orderVisitorId = order.getVisitorId();
                    orderAccompanyerId = order.getAccompanyerId();
                }

            } else {
                return new CommonResult(400, "注解的使用:operateOn=user/request/order");
            }

            //校验当前登录用户与操作内容所属用户是否一致
            if (Objects.equals(JWTUserId, userId)||Objects.equals(JWTUserId, requestVisitorId)
                    ||Objects.equals(JWTUserId, orderVisitorId)||Objects.equals(JWTUserId, orderAccompanyerId)) {
                return proceedingJoinPoint.proceed();
            } else {
                return new CommonResult(401, "用户验证信息与所操作的" + operateObjectType + "所属人不符");
            }

        } catch (Throwable e) {
            return new CommonResult(401, "非法用户验证信息");
        }
    }


}
